package com.fa4j.system.login.service.impl;

import com.fa4j.common.base.exception.CommonServerError;
import com.fa4j.common.web.model.AppType;
import com.fa4j.system.login.model.LoginAppProps;
import com.fa4j.system.login.model.LoginSettings;
import com.fa4j.system.login.model.LoginType;
import com.fa4j.system.login.service.LoginPropsService;
import com.fa4j.system.settings.service.SystemSettingsService;
import com.fa4j.third.base.service.ThirdConfigService;
import com.fa4j.third.user.model.ThirdUserGetAuthorizeParamCmd;
import com.fa4j.third.user.service.ThirdUserOauth2Service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 登录配置服务
 */
@Service
@RequiredArgsConstructor
public class LoginPropsServiceImpl implements LoginPropsService {


    private final ThirdUserOauth2Service thirdUserOauth2Service;
    private final SystemSettingsService systemSettingsService;

    private final ThirdConfigService thirdConfigService;

    /**
     * 根据应用类型获取配置
     *
     * @param appType 应用类型
     * @return 应用类型配置
     */
    @Override
    public LoginAppProps getAppTypeItemProp(AppType appType) {
        return systemSettingsService
                .getSettings("LOGIN_PROPS_" + appType.name(), LoginAppProps.class)
                .orElseThrow(() -> CommonServerError.NOT_SETTING.build("应用类型" + appType));
    }

    /**
     * 查询登录配置
     *
     * @param appType 应用类型
     * @return 登录配置
     */
    @Override
    public LoginSettings queryLoginSettings(AppType appType, String redirectUri) {
        LoginAppProps prop = getAppTypeItemProp(appType);
        Map<LoginType, Map<String, String>> loginTypeParams = new TreeMap<>();
        for (LoginType loginType : prop.getLoginTypes()) {
            if (loginType.getThirdBizCode() == null) {
                loginTypeParams.put(loginType, new HashMap<>());
            } else if (thirdConfigService.hasBizCode(loginType.getThirdBizCode())) {
                if (loginType.getThirdBizCode().startsWith("USER_OATH2")) {
                    ThirdUserGetAuthorizeParamCmd authorizeParamCmd = new ThirdUserGetAuthorizeParamCmd();
                    authorizeParamCmd.setBizCode(loginType.getThirdBizCode());
                    authorizeParamCmd.setRedirectUri(redirectUri + "&loginType=" + loginType.name());
                    loginTypeParams.put(loginType, thirdUserOauth2Service.getAuthorizeParams(authorizeParamCmd));
                } else {
                    loginTypeParams.put(loginType, new HashMap<>());
                }
            }
        }
        LoginSettings settings = new LoginSettings();
        settings.setRegisterEnable(prop.isRegisterEnabled());
        settings.setLoginTypeParams(loginTypeParams);
        return settings;
    }
}
